//
//  SEGPgcIDManager.m
//  Commom
//
//  Created by Clavis on 2020/5/7.
//

#import "SEGPgcIDManager.h"

#if __has_include(<Commom/SEGPlatformManager.h>)
#import <Commom/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#define SEGPgcOriginIDUserDefaultKey @"SEGPgcOriginIDUserDefaultKey"
#define SEGPgcAvailableIDUserDefaultKey @"SEGPgcAvailableIDUserDefaultKey"
#define SEGPgcCurrentIDUserDefaultKey @"SEGPgcCurrentIDUserDefaultKey"
#define SEGPgcManualRefreshCount 20


@interface SEGPgcIDManager ()

/// 原始未去重ID数组
@property (nonatomic, strong) NSArray *originalIDArray;
/// 不重复&未使用的ID数组
@property (nonatomic, strong) NSArray *availableIDArray;
/// 当前可用的ID 最多20条
@property (nonatomic, strong) NSArray *currentIDArray;

@end

@implementation SEGPgcIDManager

singleton_m(SEGPgcIDManager);

- (instancetype)init {
    self = [super init];
    if (self) {
        // 读取缓存
        [self getLocalData];
    }
    return self;
}

/// 获取当前可用刷新的ID
/// @param completeBlock 计算完成的回调
- (void)getCurrentRefreshID:(void(^)(NSArray *pgcIDArray))completeBlock {
    
    
}

/// 计算当前可用ID
- (void)calculateCurrentAvailableID {
    if (self.currentIDArray.count >= SEGPgcManualRefreshCount) {
        return;
    }
    
    NSMutableSet *noRepeatIDSet = [NSMutableSet setWithArray:self.availableIDArray];
    [noRepeatIDSet unionSet:[NSSet setWithArray:self.currentIDArray]];
    [noRepeatIDSet minusSet:[NSSet setWithArray:self.currentIDArray]];
    NSArray *availableIDArray = noRepeatIDSet.allObjects;
    
    // 计算还可以补齐的个数
    NSInteger leftCount = MIN(SEGPgcManualRefreshCount-self.currentIDArray.count, availableIDArray.count);
    NSArray *leftArray = [self.availableIDArray subarrayWithRange:NSMakeRange(0, leftCount)];
    self.currentIDArray = [self.currentIDArray arrayByAddingObjectsFromArray:leftArray];
}

/// 请求PGCID
- (void)requestPGCDailyIDWithFinish:(SEGNetworkReponse)finished {
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/index/daily/getDailyId",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (isSuccessed && [result isKindOfClass:[NSDictionary class]] && [result[@"data"] isKindOfClass:[NSDictionary class]] && [result[@"data"][@"other"] isKindOfClass:[NSArray class]] && [result[@"data"][@"other"] count] > 0) {
            // 数据不为空 去重后保存数据
            NSArray *newIDArray = result[@"data"][@"other"];
            NSMutableSet *oldIDSet = [NSMutableSet setWithArray:self.originalIDArray];
            NSMutableSet *newIDSet = [NSMutableSet setWithArray:newIDArray];
            [oldIDSet unionSet:newIDSet];
            [oldIDSet minusSet:[NSSet setWithArray:self.originalIDArray]];
            NSArray *noRepeatIDArray = [oldIDSet allObjects];
            self.originalIDArray = newIDArray;
            self.availableIDArray = noRepeatIDArray;
            //缓存到本地
            [self saveData];
        }
        finished(isSuccessed,result,codeType,errorMessage);
    }];
}

/// 更新ID缓存 去掉已经使用用的ID
/// @param pgcIDArray pgcIDArray
- (void)updateLocalIDWithAlreadyUsedID:(NSArray*)pgcIDArray {
    NSMutableSet *availableIDSet = [NSMutableSet setWithArray:self.availableIDArray];
    [availableIDSet unionSet:[NSSet setWithArray:pgcIDArray]];
    [availableIDSet minusSet:[NSSet setWithArray:pgcIDArray]];
    self.availableIDArray = availableIDSet.allObjects;
    self.currentIDArray = [NSArray array];
    [self saveData];
}

#pragma mark - PGC ID 数据本地缓存
- (void)saveData {
    // 保存原始数据
    [[NSUserDefaults standardUserDefaults] setObject:self.originalIDArray forKey:SEGPgcOriginIDUserDefaultKey];
    [[NSUserDefaults standardUserDefaults] setObject:self.availableIDArray forKey:SEGPgcAvailableIDUserDefaultKey];
    [[NSUserDefaults standardUserDefaults] setObject:self.currentIDArray forKey:SEGPgcCurrentIDUserDefaultKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/// 获取本地缓存广告展示数据
- (void)getLocalData{
    self.originalIDArray = [[NSUserDefaults standardUserDefaults] objectForKey:SEGPgcOriginIDUserDefaultKey];
    self.availableIDArray = [[NSUserDefaults standardUserDefaults] objectForKey:SEGPgcAvailableIDUserDefaultKey];
    self.currentIDArray = [[NSUserDefaults standardUserDefaults] objectForKey:SEGPgcCurrentIDUserDefaultKey];
}

#pragma mark - Getter
- (NSArray *)availableIDArray {
    if (!_availableIDArray) {
        _availableIDArray = [NSArray array];
    }
    return _availableIDArray;
}

- (NSArray *)originalIDArray {
    if (!_originalIDArray) {
        _originalIDArray = [NSArray array];
    }
    return _originalIDArray;
}

- (NSArray *)currentIDArray {
    if (!_currentIDArray) {
        _currentIDArray = [NSArray array];
    }
    return _currentIDArray;
}

@end
